package com.cj.display_sys

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

abstract class BaseFragment<VM : ViewModel> : Fragment() {

    private var mContext: Context? = null
    private var mRoot: View? = null
    lateinit var viewModel: VM

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        providerVMClass()?.let {
            viewModel = ViewModelProvider(this).get(it)
        }
        val layoutId = getContentLayoutId()
        // 初始化当前的根布局, 但是不在创建时就添加到 container 里面
        mRoot = inflater.inflate(layoutId, container, false)
        mContext = context
        return mRoot
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        show()
        findView()
        init()
        setListener()
    }

    abstract fun providerVMClass(): Class<VM>?

    /**
     * 得到当前界面的资源文件 id
     *
     * @return 资源文件 id
     */
    abstract fun getContentLayoutId(): Int

    /**
     * TODO<显示数据>
     *
     * @return void
     * @throw
    </显示数据> */
    abstract fun show()

    /**
     * TODO<初始化控件>
     *
     * @return void
     * @throw
    </初始化控件> */
    abstract fun findView()

    /**
     * TODO<初始化数据>
     *
     * @return void
     * @throw
    </初始化数据> */
    abstract fun init()

    /**
     * TODO<设置监听器>
     *
     * @return void
     * @throw
    </设置监听器> */
    abstract fun setListener()


    override fun onDestroyView() {
        super.onDestroyView()
        if (mRoot != null) {
            mRoot = null
        }
        if (mContext != null) {
            mContext = null
        }
    }
}